using System.Collections.Generic;
using CGF;
using LitJson;
using UnityEngine;
using Random = UnityEngine.Random;

public class RankingManager
{
    public class Player
    {
        public string name;
        public string score;
    }

    public static List<Player> ranking = new List<Player>();
    private static List<string> names = new List<string>();
    private static List<string> scroes = new List<string>();

    private static float marqueeTimer;

    public static async void StartRun()
    {
        int listSize = 50;

        if (names.Count == 0)
        {
            TextAsset asset = await ResManager.Instance.LoadAsset<TextAsset>("Configs/names");
            string[] arr = asset.text.Split("\n");
            for (int i = 0; i < arr.Length; i++)
            {
                string name = arr[i];
                if (!string.IsNullOrWhiteSpace(name))
                {
                    string nameStar = name.Substring(0, 6) + "******";
                    names.Add(nameStar);
                }
            }
        }

        if (scroes.Count == 0)
        {
            TextAsset asset = await ResManager.Instance.LoadAsset<TextAsset>("Configs/scroes");
            JsonData json = JsonMapper.ToObject(asset.text);
            for (int i = 0; i < json.Count; i++)
            {
                scroes.Add(json[i].ToString());
            }
        }

        if (ranking.Count == 0)
        {
            for (int i = 0; i < listSize; i++)
            {
                Player player = new Player() { name = names[i], score = scroes[i].ToString() };
                ranking.Add(player);
            }

            ranking.Sort((a, b) => float.Parse(b.score).CompareTo(float.Parse(a.score)));
        }

        CGFramework.Instance.updateAction += AutoPushToMarquee;
    }

    private static void AutoPushToMarquee()
    {
        if (marqueeTimer < Time.time)
        {
            marqueeTimer = Time.time + Random.Range(10, 30);
            if (Marquee.CurrQueueCount < 5)
            {
                string name = names[Random.Range(0, names.Count)];
                string score = Random.Range(10, 50) + "." + Random.Range(10, 100);
                Marquee.PushMsg($"Parabéns a {name} por concluir o pedido de venda {CGF.I18N.Currency}{score}.");
            }
        }
    }
}